package com.byq.mm.abstractx.cluster.server;

import com.byq.mm.abstractx.cluster.provider.ClusterProviderManager;
import com.byq.mm.abstractx.cluster.server.access.SecuredServer;
import com.byq.mm.abstractx.device.Cluster;
import com.byq.mm.abstractx.device.Device;
import com.byq.mm.abstractx.engine.CoreEnvironment;
import com.byq.mm.abstractx.protocol.Interaction;

import java.lang.reflect.Constructor;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;



public class DeviceServer  extends SecuredServer {
	ServerIdentifier id;
	Device device;
	Map<String, ClusterServer> servers = new HashMap<String, ClusterServer>();
	CoreEnvironment env;

	public Device getDevice() {
		return device;
	}



	public Collection<ClusterServer> getClusterServers(){
		return servers.values();
	}
	public DeviceServer(Device device, CoreEnvironment e) {
		super(e);
		this.device = device;
		this.env = e;
		id = new ServerIdentifier(device.getId(), null);
		for (Cluster c : device.getSupportedClusters()) {
			Class<? extends ClusterServer> type = ClusterProviderManager.getServerType(c.getId());

			Constructor<? extends ClusterServer> con;
			try {
				con = type.getConstructor(String.class, Device.class, CoreEnvironment.class);
				ClusterServer cc = con.newInstance(c.getId(), device, env);
				servers.put(c.getId(), cc);
			} catch (Exception e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}

		}
	}


	private SmartServer getSecureClusterServer(String clusterId) {
		ClusterServer cs =  servers.get(clusterId);
		if(cs == null)
			return null;
		return cs.getServerAccessController();
	}
	public ClusterServer getClusterServer(String clusterId) {
		return servers.get(clusterId);
		
	}


	@Override
	public boolean onCommand(Interaction i, String transport) {
		SmartServer cs = getSecureClusterServer(i.cluster);
		if(cs == null)
			return false;
		return cs.onCommand(i, transport);
	}



	@Override
	public ServerIdentifier getId() {
		// TODO Auto-generated method stub
		return id;
	}


}